<template>
  <div> <!-- Root element to satisfy vue/valid-template-root -->
    <div class="min-h-screen flex flex-col bg-gray-50">
        <!-- 顶部导航栏 -->
        <nav class="bg-emerald-600 text-white shadow-md">
            <div class="container mx-auto px-4 py-3 flex justify-between items-center">
                <div class="flex items-center space-x-2">
                    <i class="fas fa-leaf text-2xl"></i>
                    <span class="text-xl font-bold">营养师后台管理系统</span>
                </div>
                <div class="flex items-center space-x-4">
                    <a href="javascript:void(0);" class="hover:text-emerald-200 relative">
                        <i class="fas fa-bell"></i>
                        <span class="bg-red-500 text-white rounded-full w-5 h-5 text-xs flex items-center justify-center absolute -mt-8 ml-3">3</span>
                    </a>
                    <div class="relative group">
                        <div class="flex items-center space-x-2 cursor-pointer">
                            <img src="https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=150&h=150&q=80" 
                                class="w-8 h-8 rounded-full object-cover" alt="用户头像">
                            <span>管理员</span>
                            <i class="fas fa-chevron-down text-xs"></i>
                        </div>
                        <div class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-50 hidden group-hover:block">
                            <a href="javascript:void(0);" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                                <i class="fas fa-user mr-2"></i>个人信息
                            </a>
                            <a href="javascript:void(0);" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                                <i class="fas fa-cog mr-2"></i>系统设置
                            </a>
                            <div class="border-t border-gray-200 my-1"></div>
                            <a href="javascript:void(0);" @click="logout" class="block px-4 py-2 text-gray-800 hover:bg-emerald-100">
                                <i class="fas fa-sign-out-alt mr-2"></i>退出登录
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 主要内容区 -->
        <div class="flex flex-1">
            <!-- 侧边导航 -->
            <aside class="bg-white w-64 shadow-md">
                <div class="p-4">
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                            <i class="fas fa-search text-gray-400"></i>
                        </span>
                        <input type="text" v-model="searchTerm" @input="debouncedFetchFoods" class="pl-10 pr-4 py-2 w-full rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" 
                            placeholder="搜索食物...">
                    </div>
                </div>
                <nav class="mt-2">
                    <router-link to="/dashboard" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-home mr-3"></i>
                        <span>仪表盘</span>
                    </router-link>
                    <router-link to="/users" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-users mr-3"></i>
                        <span>用户管理</span>
                    </router-link>
                    <router-link to="/foods" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-apple-alt mr-3"></i>
                        <span>食物数据库</span>
                    </router-link>
                    <router-link to="/recipes" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-utensils mr-3"></i>
                        <span>食谱管理</span>
                    </router-link>
                    <router-link to="/diet-records" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-clipboard-list mr-3"></i>
                        <span>饮食记录</span>
                    </router-link>
                    <router-link to="/nutrition" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-chart-pie mr-3"></i>
                        <span>营养分析</span>
                    </router-link>
                    <router-link to="/settings" class="flex items-center px-4 py-3 text-gray-700 hover:bg-gray-50 hover:text-emerald-600" active-class="text-emerald-600 bg-emerald-50 border-l-4 border-emerald-600">
                        <i class="fas fa-cog mr-3"></i>
                        <span>系统设置</span>
                    </router-link>
                </nav>
            </aside>

            <!-- 主内容 -->
            <main class="flex-1 p-6">
                <div class="mb-6 flex justify-between items-center">
                    <div>
                        <h1 class="text-2xl font-bold text-gray-800">食物数据库</h1>
                        <p class="text-gray-600">管理食物数据、分类和营养信息</p>
                    </div>
                    <button @click="openAddFoodModal" class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-md flex items-center">
                        <i class="fas fa-plus mr-2"></i>
                        <span>添加食物</span>
                    </button>
                </div>

                <!-- 食物分类 -->
                <div class="mb-6">
                    <h2 class="text-lg font-medium text-gray-800 mb-3">食物分类</h2>
                    <div class="flex flex-wrap gap-2">
                        <button 
                            v-for="category in foodCategories" 
                            :key="category.id"
                            @click="setActiveCategory(category.id)"
                            :class="[
                                'px-4 py-2 rounded-md flex items-center text-sm',
                                activeCategoryId === category.id ? 'bg-emerald-600 text-white' : 'bg-white hover:bg-gray-50 text-gray-700 border border-gray-300'
                            ]"
                        >
                            <template v-if="category.icon">
                                <img 
                                    v-if="category.icon.startsWith('/') || category.icon.startsWith('http')" 
                                    :src="getFullFoodImageUrl(category.icon)" 
                                    alt=""
                                    class="mr-2 h-4 w-4 object-contain" 
                                    @error="onCategoryIconError" />
                                <i 
                                    v-else-if="typeof category.icon === 'string' && category.icon.includes('fa-')" 
                                    :class="['mr-2', category.icon, category.iconColor || '']">
                                </i>
                                <span v-else class="mr-2 h-4 w-4 inline-block"></span> 
                            </template>
                            {{ category.name }}
                        </button>
                    </div>
                </div>

                <!-- 筛选和搜索 -->
                <div class="bg-white rounded-lg shadow-md p-4 mb-6">
                    <div class="flex flex-wrap gap-4">
                        <div class="relative flex-grow md:max-w-xs">
                            <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                                <i class="fas fa-search text-gray-400"></i>
                            </span>
                            <input type="text" v-model="searchTerm" @input="debouncedFetchFoods" class="pl-10 pr-4 py-2 w-full rounded-md border border-gray-300 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" 
                                placeholder="搜索食物...">
                        </div>
                        
                        <div class="flex items-center space-x-4 flex-wrap">
                            <select v-model="filterNutrient" @change="applyFilters" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                                <option value="">营养素筛选</option>
                                <option value="high_protein">高蛋白</option>
                                <option value="low_fat">低脂肪</option>
                                <option value="low_carb">低碳水</option>
                                <option value="high_fiber">高纤维</option>
                            </select>
                            
                            <select v-model="filterStatus" @change="applyFilters" class="border border-gray-300 rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                                <option value="">所有状态</option>
                                <option value="true">已验证</option>
                                <option value="false">未验证</option>
                            </select>
                        </div>
                        
                        <button @click="applyFiltersAndResetPage" class="bg-emerald-600 hover:bg-emerald-700 text-white px-4 py-2 rounded-md ml-auto">
                            筛选
                        </button>
                    </div>
                </div>

                <!-- Loading Indicator -->
                <div v-if="isLoading" class="text-center py-10">
                    <i class="fas fa-spinner fa-spin text-emerald-600 text-3xl"></i>
                    <p class="text-gray-600 mt-2">加载中...</p>
                </div>

                <!-- Error Message -->
                <div v-if="apiError" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4" role="alert">
                    <strong class="font-bold">错误!</strong>
                    <span class="block sm:inline"> {{ apiError }}</span>
                </div>

                <!-- 食物列表 -->
                <div v-if="!isLoading && !apiError && foodItems.length > 0" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                    <div v-for="food_item in foodItems" :key="food_item._id || food_item.id" class="bg-white rounded-lg shadow-md overflow-hidden">
                        <div class="relative">
                            <img :src="getFullFoodImageUrl(food_item.image)" class="w-full h-40 object-cover" alt="食物图片" @error="onImageError">
                            <div class="absolute top-2 left-2">
                                <span :class="['text-white text-xs px-2 py-1 rounded-full', food_item.isVerified ? 'bg-green-500' : 'bg-yellow-500']">
                                    {{ food_item.isVerified ? '已验证' : '未验证' }}
                                </span>
                            </div>
                            <div class="absolute top-2 right-2">
                                <button class="bg-white text-gray-600 rounded-full w-8 h-8 flex items-center justify-center shadow-md hover:bg-gray-100">
                                    <i class="fas fa-ellipsis-v"></i>
                                </button>
                            </div>
                        </div>
                        <div class="p-4">
                            <h3 class="text-lg font-medium text-gray-800">{{ food_item.name }}</h3>
                            <p class="text-gray-500 text-sm">{{ food_item.category && food_item.category.name ? food_item.category.name : '无分类' }}</p>
                            <div class="mt-3 flex justify-between items-center">
                                <div>
                                    <p class="text-gray-600 text-sm">{{ food_item.unit || '100克' }}</p>
                                    <p class="text-lg font-semibold text-emerald-600">{{ food_item.calories }} kcal</p>
                                </div>
                                <div class="space-y-1">
                                    <div class="flex items-center text-xs">
                                        <span class="text-gray-500 w-20">蛋白质:</span>
                                        <span class="font-medium">Protein Placeholder</span>
                                    </div>
                                    <div class="flex items-center text-xs">
                                        <span class="text-gray-500 w-20">脂肪:</span>
                                        <span class="font-medium">Fat Placeholder</span>
                                    </div>
                                    <div class="flex items-center text-xs">
                                        <span class="text-gray-500 w-20">碳水:</span>
                                        <span class="font-medium">Carbs Placeholder</span>
                                    </div>
                                </div>
                            </div>
                            <div class="mt-4 flex space-x-2">
                                <button @click="editFood(food_item)" class="flex-1 bg-emerald-100 hover:bg-emerald-200 text-emerald-600 py-2 rounded text-sm">
                                    <i class="fas fa-edit mr-1"></i> 编辑
                                </button>
                                <button @click="viewFood(food_item._id || food_item.id)" class="flex-1 bg-gray-100 hover:bg-gray-200 text-gray-600 py-2 rounded text-sm">
                                    <i class="fas fa-eye mr-1"></i> 查看
                                </button>
                                <button @click="handleDeleteFood(food_item._id || food_item.id)" class="flex-1 bg-red-100 hover:bg-red-200 text-red-600 py-2 rounded text-sm">
                                    <i class="fas fa-trash-alt mr-1"></i> 删除
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div v-if="!isLoading && foodItems.length === 0 && !apiError" class="text-center py-10">
                    <p class="text-gray-600">未找到食物数据。</p>
                </div>

                <!-- 分页 -->
                <div v-if="!isLoading && totalPages > 1" class="mt-6 flex justify-center">
                    <nav class="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                        <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" 
                                class="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <button v-for="pageNumber in paginationRange" :key="pageNumber" 
                                @click="changePage(pageNumber)"
                                :class="['relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium',
                                         pageNumber === currentPage ? 'bg-emerald-50 text-emerald-600 z-10' : 'bg-white text-gray-700 hover:bg-gray-50']">
                            {{ pageNumber === '...' ? '...' : pageNumber }}
                        </button>
                        <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages"
                                class="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </nav>
                </div>
            </main>
        </div>
    </div>

    <!-- 添加/编辑食物模态框 -->
    <div v-if="showFoodModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg shadow-lg w-full max-w-3xl mx-4 overflow-hidden">
            <div class="bg-emerald-600 text-white px-6 py-4 flex justify-between items-center">
                <h3 class="text-lg font-medium">{{ isEditing ? '编辑食物' : '添加新食物' }}</h3>
                <button @click="closeFoodModal" type="button" class="text-white hover:text-gray-200 focus:outline-none">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <div class="px-6 py-4 max-h-[80vh] overflow-y-auto">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h4 class="text-md font-medium text-gray-700 mb-4">基本信息</h4>
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="foodName">
                                食物名称 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" v-model="foodForm.name" id="foodName" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入食物名称">
                            <p v-if="foodFormErrors.name" class="mt-1 text-sm text-red-600">{{ foodFormErrors.name }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="foodCategoryModal">
                                食物分类 <span class="text-red-500">*</span>
                            </label>
                            <select v-model="foodForm.category" id="foodCategoryModal" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500">
                                <option value="">选择分类</option>
                                <option v-for="category in availableCategoriesForForm" :key="category.id" :value="category.id">
                                    {{ category.name }}
                                </option>
                            </select>
                            <p v-if="foodFormErrors.category" class="mt-1 text-sm text-red-600">{{ foodFormErrors.category }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="servingUnitInput">
                                计量单位 <span class="text-red-500">*</span>
                            </label>
                            <input type="text" v-model="foodForm.unit" id="servingUnitInput" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="如: 克, 100克, 个">
                             <p v-if="foodFormErrors.unit" class="mt-1 text-sm text-red-600">{{ foodFormErrors.unit }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">食物状态</label>
                            <div class="flex space-x-4">
                                <label class="inline-flex items-center">
                                    <input type="radio" v-model="foodForm.isVerified" :value="true" class="form-radio text-emerald-600 focus:ring-emerald-500">
                                    <span class="ml-2">已验证</span>
                                </label>
                                <label class="inline-flex items-center">
                                    <input type="radio" v-model="foodForm.isVerified" :value="false" class="form-radio text-yellow-500 focus:ring-yellow-500">
                                    <span class="ml-2">待验证</span>
                                </label>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1">食物图片</label>
                            <div class="mt-1 flex items-center">
                                <div class="w-24 h-24 rounded-md border border-gray-300 flex items-center justify-center bg-gray-100 text-gray-400 overflow-hidden">
                                    <img v-if="imagePreviewUrl" :src="imagePreviewUrl" class="w-full h-full object-cover" alt="图片预览">
                                    <i v-else class="fas fa-image text-2xl"></i>
                                </div>
                                <button type="button" @click="triggerImageUpload" class="ml-4 bg-white border border-gray-300 text-gray-700 px-3 py-2 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2">
                                    上传图片
                                </button>
                                <input type="file" ref="foodImageInputRef" @change="handleImageSelected" accept="image/*" class="hidden">
                            </div>
                             <p v-if="foodForm.image && !imagePreviewUrl && isEditing" class="mt-1 text-xs text-gray-500">当前图片: <a :href="getFullFoodImageUrl(foodForm.image)" target="_blank" class="text-emerald-600 hover:underline">查看</a></p>
                            <p class="mt-1 text-xs text-gray-500">推荐尺寸: 300x200 像素，格式: JPG、PNG</p>
                        </div>
                    </div>

                    <div>
                        <h4 class="text-md font-medium text-gray-700 mb-4">营养成分信息 (每100克/毫升)</h4>
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="calories">
                                热量 (kcal) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" v-model.number="foodForm.calories" id="calories" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入热量">
                            <p v-if="foodFormErrors.calories" class="mt-1 text-sm text-red-600">{{ foodFormErrors.calories }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="protein">
                                蛋白质 (g) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" v-model.number="foodForm.nutrition.protein" step="0.1" id="protein" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入蛋白质含量">
                            <p v-if="foodFormErrors.protein" class="mt-1 text-sm text-red-600">{{ foodFormErrors.protein }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="fat">
                                脂肪 (g) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" v-model.number="foodForm.nutrition.fat" step="0.1" id="fat" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入脂肪含量">
                            <p v-if="foodFormErrors.fat" class="mt-1 text-sm text-red-600">{{ foodFormErrors.fat }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="carbs">
                                碳水化合物 (g) <span class="text-red-500">*</span>
                            </label>
                            <input type="number" v-model.number="foodForm.nutrition.carbohydrate" step="0.1" id="carbs" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入碳水化合物含量">
                            <p v-if="foodFormErrors.carbs" class="mt-1 text-sm text-red-600">{{ foodFormErrors.carbs }}</p>
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="fiber">
                                膳食纤维 (g)
                            </label>
                            <input type="number" v-model.number="foodForm.nutrition.fiber" step="0.1" id="fiber" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="请输入膳食纤维含量">
                        </div>

                        <div class="mb-4">
                            <label class="block text-sm font-medium text-gray-700 mb-1" for="notes">
                                备注
                            </label>
                            <textarea v-model="foodForm.notes" id="notes" rows="3" class="w-full rounded-md border border-gray-300 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:border-emerald-500" placeholder="添加关于这个食物的其他信息"></textarea>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-gray-50 px-6 py-4 flex justify-end space-x-3">
                <button type="button" @click="closeFoodModal" class="bg-white border border-gray-300 text-gray-700 px-4 py-2 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-gray-500 focus:ring-offset-2">
                    取消
                </button>
                <button type="button" @click="submitFoodForm" class="bg-emerald-600 text-white px-4 py-2 rounded-md hover:bg-emerald-700 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-offset-2" :disabled="isSubmitting">
                    {{ isSubmitting ? '提交中...' : (isEditing ? '保存更改' : '添加食物') }}
                </button>
            </div>
        </div>
    </div>

    <!-- 新的食物详情模态框 -->
    <FoodDetailModal 
      :food="selectedFoodDetail" 
      :visible="showDetailModal" 
      @close="showDetailModal = false"
    />

  </div> <!-- Closing the root element -->
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import FoodDetailModal from '@/components/FoodDetailModal.vue'; // 移到前面
import { searchFoods, getFoodDetail, getFullFoodImageUrl, getAllFoodCategories, addFood, deleteFood } from '@/api/foods';
import { getAllFoodCategories as apiGetAllFoodCategories } from '@/api/foods'; // Alias for clarity if needed
import { debounce } from 'lodash-es';
import { useAuthStore } from '../stores/auth'
import { useRouter } from 'vue-router';

const authStore = useAuthStore();
const router = useRouter();

const isLoading = ref(false);
const apiError = ref(null);
const showFoodModal = ref(false);
const isEditing = ref(false);
const isSubmitting = ref(false);
const editingFoodId = ref(null);

const foodImageInputRef = ref(null);
const imagePreviewUrl = ref('');
const selectedImageFile = ref(null); // Will hold the File object for new/updated image

const placeholderImage = 'https://dummyimage.com/300x200/cccccc/000000.png&text=Image+Not+Found';

/* Comment out the local function definition to avoid conflict with the imported one
function getFullFoodImageUrl(imagePath) { // Assuming this is the local definition causing issues
  try {
    if (!imagePath) return placeholderImage;
    // Ensure this calls the imported function if that was the intent, or has unique logic
    return apiGetFullFoodImageUrl(imagePath); // If it was just a wrapper
  } catch (error) {
    console.error('[FoodsView] 获取食物图片URL失败:', error);
    return placeholderImage;
  }
}
*/

function onImageError(event) {
  event.target.src = placeholderImage;
}

const formatNutritionDisplay = (value) => {
  const num = parseFloat(value);
  if (isNaN(num)) {
    return '0g'; // Or 'N/A', or handle as preferred
  }
  return `${num}g`;
};

const initialFoodForm = () => ({
    _id: null,
    name: '',
    category: '', // This will be category ID for submission
    image: '', // Path from API or for new upload
    unit: '克', // Default unit
    calories: null,
    nutrition: {
        protein: null,
        fat: null,
        carbohydrate: null,
        fiber: null,
        // sugar, sodium, cholesterol can be added if needed for form
    },
    isVerified: true, // Default status
    notes: ''
});

const foodForm = reactive(initialFoodForm());
const foodFormErrors = reactive({
    name: '',
    category: '',
    unit: '',
    calories: '',
    protein: '',
    fat: '',
    carbs: ''
});

// Local categories for UI, ideally these would come from an API
// The `id` here should match the `categoryId` the backend expects.
const foodCategories = ref([]); // Initialize as an empty array
const activeCategoryId = ref(null);

const searchTerm = ref('');
const filterNutrient = ref('');
const filterStatus = ref('');

// Pagination state
const currentPage = ref(1);
const itemsPerPage = ref(8); // Or any default you prefer, matching your grid likely
const totalFoodItems = ref(0);
const totalPages = ref(0);

const showDetailModal = ref(false);
const selectedFoodDetail = ref(null);

const fetchFoods = async () => {
  isLoading.value = true;
  apiError.value = null;
  console.log('fetchFoods called with filters:', { 
    name: searchTerm.value, 
    categoryId: activeCategoryId.value,
    filterNutrient: filterNutrient.value,
    status: filterStatus.value,
    page: currentPage.value 
  });

  const params = {
    page: currentPage.value,
    limit: itemsPerPage.value,
    sortBy: 'createdAt',
    sortOrder: 'desc',
  };

  if (searchTerm.value) {
    params.name = searchTerm.value;
  }
  if (activeCategoryId.value && activeCategoryId.value !== 'all') { // Make sure 'all' is not sent as ID
    params.categoryId = activeCategoryId.value;
  }

  // Nutrient filter logic
  if (filterNutrient.value) {
    const nutrientMap = {
      'high_protein': { nutrient: 'protein', min: 20 }, // Example: Protein >= 20g
      'low_fat': { nutrient: 'fat', max: 5 },         // Example: Fat <= 5g
      'low_carb': { nutrient: 'carbohydrate', max: 10 },// Example: Carbs <= 10g
      'high_fiber': { nutrient: 'fiber', min: 5 }     // Example: Fiber >= 5g
    };
    const selectedNutrientFilter = nutrientMap[filterNutrient.value];
    if (selectedNutrientFilter) {
      params.nutrient = selectedNutrientFilter.nutrient;
      if (selectedNutrientFilter.min !== undefined) {
        params.nutrientMin = selectedNutrientFilter.min;
      }
      if (selectedNutrientFilter.max !== undefined) {
        params.nutrientMax = selectedNutrientFilter.max;
      }
    }
  }
  
  if (filterStatus.value) {
    params.isVerified = filterStatus.value === 'true';
  }

  console.log('Params sent to API:', params);

  try {
    const response = await searchFoods(params);
    console.log('[FoodsView] API Response Body:', response.body); // Log the full body
    if (response && response.body && response.body.foods) {
      foodItems.value = response.body.foods.map(food => ({
        ...food,
        // Ensure category is an object, if not, transform or handle
        category: typeof food.category === 'string' ? { id: food.category, name: '未知分类' } : food.category,
        // Ensure nutrition is an object
        nutrition: food.nutrition || {} 
      }));
      // Correctly access pagination data directly from response.body
      if (response.body.totalPages !== undefined && response.body.total !== undefined) { // Check if totalPages and total exist directly
        totalPages.value = response.body.totalPages;
        totalFoodItems.value = response.body.total; 
        console.log('[FoodsView] Pagination data received (direct from body):', { totalPages: response.body.totalPages, totalItems: response.body.total });
        console.log(`[FoodsView] Total pages set to: ${totalPages.value}, Total items: ${totalFoodItems.value}`);
      } else {
        totalPages.value = 1;
        totalFoodItems.value = foodItems.value.length; // Fallback if no pagination info
        console.warn('[FoodsView] Pagination data (totalPages or total) missing in API response body. Defaulting totalPages to 1.');
      }
      
      if (currentPage.value > totalPages.value && totalPages.value > 0) {
        console.log(`[FoodsView] Current page ${currentPage.value} is greater than total pages ${totalPages.value}. Resetting to total pages.`);
        currentPage.value = totalPages.value;
        // Optionally re-fetch if page was out of bounds, but be careful of infinite loops
        // await fetchFoods(); // This could lead to a loop if not handled carefully
      } else if (totalPages.value === 0 && foodItems.value.length > 0) {
        // If API says 0 pages but we have items, assume 1 page
        totalPages.value = 1;
      }

    } else {
      foodItems.value = [];
      totalPages.value = 1;
      totalFoodItems.value = 0;
      console.warn('Unexpected API response structure for searchFoods (no body or no foods array):', response);
    }
  } catch (error) {
    console.error('Error fetching foods:', error);
    apiError.value = `获取食物列表失败: ${error.message || '请稍后再试'}`;
    foodItems.value = []; // Clear items on error
    totalPages.value = 1;
     // Fallback to mock data if API fails (optional, for development)
    // console.warn('API request failed, attempting to load mock data.');
    // try {
    //   const mockData = await getMockFoods(params);
    //   if (mockData && mockData.body && mockData.body.foods) {
    //     foodItems.value = mockData.body.foods;
    //     totalPages.value = mockData.body.pagination.totalPages;
    //     apiError.value = 'API 请求失败，已加载本地模拟数据。'; // Inform user
    //   } else {
    //     foodItems.value = [];
    //     totalPages.value = 1;
    //   }
    // } catch (mockError) {
    //   console.error('Error fetching mock foods:', mockError);
    //   foodItems.value = [];
    //   totalPages.value = 1;
    //   apiError.value = '获取食物列表及模拟数据均失败，请检查网络连接或联系管理员。';
    // }
  } finally {
    isLoading.value = false;
  }
};

const fetchFoodCategories = async () => {
  try {
    const response = await getAllFoodCategories({ activeOnly: true }); // Example: fetch only active categories
    if (response && response.body && response.body.categories) {
      // Add an "All" category at the beginning
      foodCategories.value = [
        { id: 'all', name: '全部分类', icon: 'fas fa-grip-horizontal' }, // Using 'all' as a special ID
        ...response.body.categories
      ];
      if (!activeCategoryId.value && foodCategories.value.length > 0) {
        // Optionally set the first real category (or 'all') as active by default
        // activeCategoryId.value = foodCategories.value[0].id; 
      }
    } else {
      foodCategories.value = [{ id: 'all', name: '全部分类', icon: 'fas fa-grip-horizontal' }]; // Default if API fails or returns no categories
      console.warn('Unexpected API response structure for getAllFoodCategories:', response);
    }
  } catch (error) {
    console.error('Error fetching food categories:', error);
    // Provide a default "All" category even on error, or handle error display
    foodCategories.value = [{ id: 'all', name: '全部分类', icon: 'fas fa-grip-horizontal' }];
    // Optionally, set an error message for categories
    // apiError.value = (apiError.value ? apiError.value + '\n' : '') + `获取食物分类失败: ${error.message || '请稍后再试'}`;
  }
};

const foodItems = ref([]);

function setActiveCategory(categoryId) {
    console.log(`[FoodsView] setActiveCategory called with: ${categoryId}`);
    activeCategoryId.value = categoryId;
    currentPage.value = 1; // Reset to first page when category changes
    fetchFoods();
}

function applyFilters() {
    console.log(`[FoodsView] applyFilters called. searchTerm: ${searchTerm.value}, filterNutrient: ${filterNutrient.value}, filterStatus: ${filterStatus.value}`);
    currentPage.value = 1; // Reset to first page when filters change
    fetchFoods();
}

function applyFiltersAndResetPage() {
    currentPage.value = 1;
    fetchFoods();
}

function changePage(page) {
    if (page >= 1 && page <= totalPages.value && page !== currentPage.value) {
        currentPage.value = page;
        fetchFoods();
    }
}

const paginationRange = computed(() => {
    const delta = 2;
    const left = currentPage.value - delta;
    const right = currentPage.value + delta + 1;
    const range = [];
    const rangeWithDots = [];
    let l;

    for (let i = 1; i <= totalPages.value; i++) {
        if (i === 1 || i === totalPages.value || (i >= left && i < right)) {
            range.push(i);
        }
    }

    for (let i of range) {
        if (l) {
            if (i - l === 2) {
                rangeWithDots.push(l + 1);
            } else if (i - l !== 1) {
                rangeWithDots.push('...');
            }
        }
        rangeWithDots.push(i);
        l = i;
    }
    return rangeWithDots;
});

function resetFormAndErrors() {
    Object.assign(foodForm, initialFoodForm());
    Object.keys(foodFormErrors).forEach(key => foodFormErrors[key] = '');
    imagePreviewUrl.value = '';
    selectedImageFile.value = null;
    if (foodImageInputRef.value) {
        foodImageInputRef.value.value = '';
    }
}

function openAddFoodModal() {
    isEditing.value = false;
    editingFoodId.value = null;
    resetFormAndErrors();
    showFoodModal.value = true;
}

function closeFoodModal() {
    showFoodModal.value = false;
}

function triggerImageUpload() {
    foodImageInputRef.value?.click();
}

function handleImageSelected(event) {
    const file = event.target.files?.[0];
    if (file) {
        selectedImageFile.value = file; // Store the File object
        const reader = new FileReader();
        reader.onload = (e) => {
            imagePreviewUrl.value = e.target?.result;
        };
        reader.readAsDataURL(file);
        foodForm.image = ''; // Clear existing image path if new one is selected
    } else {
        selectedImageFile.value = null;
        // Don't clear imagePreviewUrl if no file is chosen, to keep existing preview if any
    }
}

function validateFoodForm() {
    let isValid = true;
    Object.keys(foodFormErrors).forEach(key => foodFormErrors[key] = '');

    if (!foodForm.name.trim()) {
        foodFormErrors.name = '请输入食物名称'; isValid = false;
    }
    if (!foodForm.category) { // category is ID
        foodFormErrors.category = '请选择食物分类'; isValid = false;
    }
    if (!foodForm.unit || !foodForm.unit.trim()) {
        foodFormErrors.unit = '请输入计量单位'; isValid = false;
    }
    if (foodForm.calories === null || foodForm.calories < 0) {
        foodFormErrors.calories = '请输入有效的热量值'; isValid = false;
    }
    if (foodForm.nutrition.protein === null || foodForm.nutrition.protein < 0) {
        foodFormErrors.protein = '请输入有效的蛋白质值'; isValid = false;
    }
    if (foodForm.nutrition.fat === null || foodForm.nutrition.fat < 0) {
        foodFormErrors.fat = '请输入有效的脂肪值'; isValid = false;
    }
    if (foodForm.nutrition.carbohydrate === null || foodForm.nutrition.carbohydrate < 0) {
        foodFormErrors.carbs = '请输入有效的碳水化合物值'; isValid = false;
    }
    return isValid;
}

async function submitFoodForm() {
    if (!validateFoodForm()) return;

    isSubmitting.value = true;
    apiError.value = null;

    // 创建一个 FormData 对象来处理文件上传
    const formData = new FormData();
    formData.append('name', foodForm.name);
    formData.append('category', foodForm.category); // category ID
    formData.append('unit', foodForm.unit);
    formData.append('calories', foodForm.calories);
    formData.append('isVerified', foodForm.isVerified);
    
    // 确保 nutrition 对象中的字段是数字或在后端能接受的类型
    formData.append('nutrition[protein]', foodForm.nutrition.protein || 0);
    formData.append('nutrition[fat]', foodForm.nutrition.fat || 0);
    formData.append('nutrition[carbohydrate]', foodForm.nutrition.carbohydrate || 0);
    formData.append('nutrition[fiber]', foodForm.nutrition.fiber || 0);
    // Add other optional nutrition fields if they are in foodForm.nutrition
    if (foodForm.nutrition.sugar !== undefined && foodForm.nutrition.sugar !== null) {
      formData.append('nutrition[sugar]', foodForm.nutrition.sugar);
    }
    if (foodForm.nutrition.sodium !== undefined && foodForm.nutrition.sodium !== null) {
      formData.append('nutrition[sodium]', foodForm.nutrition.sodium);
    }
    if (foodForm.nutrition.cholesterol !== undefined && foodForm.nutrition.cholesterol !== null) {
      formData.append('nutrition[cholesterol]', foodForm.nutrition.cholesterol);
    }

    if (foodForm.notes) {
        formData.append('notes', foodForm.notes);
    }

    // 如果有新的图片文件被选中，则添加到FormData
    if (selectedImageFile.value) {
        formData.append('image', selectedImageFile.value);
    } else if (isEditing.value && foodForm.image) {
        // 如果是编辑且没有新图片，但原表单有图片路径，则可能需要发送原图片路径
        // 这取决于后端API如何处理图片更新（例如，如果image字段未发送，则不更新图片）
        // formData.append('existingImage', foodForm.image); // 示例
    }
    
    try {
        let response;
        if (isEditing.value) {
            // TODO: 调用真实的编辑食物API
            // response = await updateFood(editingFoodId.value, formData); 
            console.log("模拟更新食物:", editingFoodId.value, Object.fromEntries(formData.entries()));
            alert('食物更新成功！(模拟，API未对接)'); 
            fetchFoods(); 
            closeFoodModal();
        } else {
            response = await addFood(formData); // Call the actual addFood API
            if (response && response.error === 0) {
                alert('食物添加成功！');
                fetchFoods(); // Re-fetch list to show the new item
                closeFoodModal();
            } else {
                throw new Error(response?.message || '添加食物失败');
            }
        }
    } catch (error) {
        console.error("Food submission error:", error);
        apiError.value = `提交失败: ${error.message || '未知错误'}`;
    } finally {
        isSubmitting.value = false;
    }
}

async function editFood(foodItemFromList) {
    isEditing.value = true;
    editingFoodId.value = foodItemFromList._id;
    resetFormAndErrors();
    isLoading.value = true; 
    apiError.value = null;

    try {
        const response = await getFoodDetail(foodItemFromList._id); // 调用真实API获取详情
        
        if (response.error === 0 && response.body) {
            const foodDetails = response.body;
            // 注意：根据API文档，获取详情时营养成分直接在body下，而不是body.nutrition
            // 而列表接口中营养成分在 body.foods[].nutrition
            // 需要统一或根据接口调整
            foodForm._id = foodDetails._id || foodDetails.id; // API返回的是 id 或 _id
            foodForm.name = foodDetails.name;
            foodForm.category = foodDetails.category?._id || foodDetails.category?.id || ''; 
            foodForm.image = foodDetails.image; 
            if (foodDetails.image) {
                 imagePreviewUrl.value = apiGetFullFoodImageUrl(foodDetails.image);
            } else {
                imagePreviewUrl.value = '';
            }
            foodForm.unit = foodDetails.unit;
            foodForm.calories = foodDetails.calories;
            
            // 假设详情API返回的营养素在顶层 (protein, fat, etc.)
            // 如果仍然在 foodDetails.nutrition 下，则用 foodDetails.nutrition?.protein
            foodForm.nutrition.protein = foodDetails.protein; 
            foodForm.nutrition.fat = foodDetails.fat;
            foodForm.nutrition.carbohydrate = foodDetails.carbohydrate;
            foodForm.nutrition.fiber = foodDetails.fiber;

            foodForm.isVerified = foodDetails.isVerified === undefined ? true : foodDetails.isVerified;
            foodForm.notes = foodDetails.notes || '';
            
            showFoodModal.value = true;
        } else {
            throw new Error(response.message || '获取食物详情失败');
        }
    } catch (error) {
        console.error('Failed to populate form for edit:', error);
        apiError.value = "准备编辑失败: " + error.message;
    } finally {
        isLoading.value = false;
    }
}

async function viewFood(foodId) {
    isLoading.value = true;
    apiError.value = null;
    try {
        const response = await getFoodDetail(foodId); 
        
        if (response.error === 0 && response.body) {
            selectedFoodDetail.value = response.body; // 将获取到的详情数据存起来
            showDetailModal.value = true; // 打开详情模态框
        } else {
            throw new Error(response.message || '获取食物详情失败');
        }
    } catch (error) {
        console.error('[FoodsView] Failed to view food details:', error);
        apiError.value = error.message || '查看详情失败。';
        // 可以选择用一个更友好的方式提示错误，例如 InfoModal
        alert('查看详情失败: ' + apiError.value); 
    }
    isLoading.value = false;
}

async function logout() {
  try {
    console.log('[FoodsView] 执行退出登录');
    // 执行认证存储的登出方法
    authStore.logout();
    // 导航到登录页
    router.push('/login');
  } catch (error) {
    console.error('[FoodsView] 退出登录出错:', error);
    alert('退出登录失败，请重试');
  }
}

// Fetch initial data
onMounted(async () => {
    console.log("[FoodsView] 组件挂载，初始化认证状态并获取数据");
    await authStore.checkAndRefreshAuth();
    fetchFoodCategories(); // Fetch categories on mount
    fetchFoods(); // Initial fetch of food items
    // TODO: 如果有获取食物分类的API，在这里调用并填充 foodCategories.value
});

// Watch for filter changes to refetch data
// watch([searchTerm, activeCategoryId, filterStatus], () => {
//     console.log("[FoodsView] Watch triggered. Re-fetching foods.");
//     // Debounced fetch is called by direct input on searchTerm
//     // For select changes, applyFilters (which calls fetchFoods) is used.
//     // This watch is a fallback or can be more specific if needed.
//     // If using debounce on searchTerm input, direct call here might be redundant
//     // applyFilters(); // Or debouncedFetchFoods() if preferred for all programmatic changes
// });

const availableCategoriesForForm = computed(() => {
  // Exclude "All" category from the form dropdown
  return foodCategories.value.filter(cat => cat.id !== 'all');
});

const onCategoryIconError = (event) => {
  // More specific placeholder or hide icon on error for category icons
  event.target.style.display = 'none'; // Or set to a default icon placeholder path
};

async function handleDeleteFood(foodId) {
  if (!foodId) {
    console.error('[FoodsView] handleDeleteFood called with invalid foodId:', foodId);
    alert('无法删除食物：无效的食物ID。');
    return;
  }

  // 使用 confirm 进行简单的用户确认
  if (!confirm('您确定要删除这个食物吗？此操作无法撤销。')) {
    return;
  }

  isLoading.value = true; // 可以考虑为删除操作设置一个单独的 loading 状态
  apiError.value = null;

  try {
    // 注意：API 文档指示成功删除返回 204 No Content，并且响应体为空。
    // request 工具可能需要配置来正确处理这种情况，或者它本身就能处理。
    // 我们假设 request 工具在 204 时会 resolve，可能不带任何 body。
    await deleteFood(foodId); 
    
    alert('食物删除成功！');
    // 重新获取食物列表以更新UI
    // 如果当前页在删除后变为空，且不是第一页，则可能需要跳转到前一页
    if (foodItems.value.length === 1 && currentPage.value > 1) {
        currentPage.value -= 1;
    }
    await fetchFoods();

  } catch (error) {
    console.error('[FoodsView] Failed to delete food:', error);
    // API文档中，错误情况会有JSON响应体
    // 需要检查 error 对象中是否包含这些信息，或者 request 工具是否已解析
    let errorMessage = '删除食物失败。';
    if (error && error.response && error.response.data && error.response.data.message) {
      errorMessage = `删除失败: ${error.response.data.message}`;
    } else if (error && error.message) {
      errorMessage = `删除失败: ${error.message}`;
    }
    apiError.value = errorMessage;
    alert(apiError.value); // 同时通过 alert 提示用户
  } finally {
    isLoading.value = false; // 重置 loading 状态
  }
}

</script>

<style scoped>
/* Component-specific styles can go here if needed, though Tailwind is used extensively. */
.max-h-\[80vh\] {
  max-height: 80vh;
}
</style> 